import flash.utils.Dictionary;
import mx.charts.ChartItem;
import mx.charts.HitData;
import mx.charts.events.ChartItemEvent;
import mx.charts.series.items.ColumnSeriesItem;
import mx.charts.series.items.PieSeriesItem;
import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.controls.Button;
import mx.controls.List;
import mx.events.ListEvent;
import mx.graphics.IFill;
import mx.managers.PopUpManager;
import mx.managers.ToolTipManager;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import utils.homeBox;
[Bindable]
private var acRatio:ArrayCollection;
[Bindable]
private var acColumn:ArrayCollection;
private var uriHome:String;
private var uriData:String;
private var dictType2Button:Dictionary;
private var dictName2Type:Dictionary;
private var dictButton2Count:Dictionary;
private var acButton:ArrayCollection;
private var _homebox:homeBox;
[Bindable]
private var _contentName:String  = '';
private var _contentID:String    = '';
private var _contentIndex:int;
[Bindable]
private var max:Number;
private var queryDate:Date;
private var queryInterval:String = MONTH;
[Bindable]
private var noData:Boolean       = false;

private function init():void
{
	ToolTipManager.showDelay = 400;
	ToolTipManager.hideDelay = 2000;
	electricid = Application.application.parameters.electricid;
	trace(electricid);
	if (electricid.length == 0)
	{
		Alert.show("尚未取得電號，請登入");
		return;
	}
	var loader:URLLoader = new URLLoader();
	loader.addEventListener(Event.COMPLETE, configLoad);
	loader.dataFormat = URLLoaderDataFormat.TEXT;
	loader.load(new URLRequest('config.xml'));
}

private function configLoad(event:Event):void
{
	acRatio = new ArrayCollection();
	acColumn = new ArrayCollection();
	acButton = new ArrayCollection();
	dictButton2Count = new Dictionary();
	cbSelector.addEventListener(ListEvent.CHANGE, selectorChange);
	btnDay.addEventListener(MouseEvent.CLICK, switchRange);
	btnMonth.addEventListener(MouseEvent.CLICK, switchRange);
	btnYear.addEventListener(MouseEvent.CLICK, switchRange);
	btnLeft.addEventListener(MouseEvent.CLICK, scrollRange);
	btnRight.addEventListener(MouseEvent.CLICK, scrollRange);
	var loader:URLLoader = event.currentTarget as URLLoader;
	var xml:XML          = new XML(loader.data);
	uriData = xml.EquipmentUsage;
	uriHome = xml.LoadHome;
	createDict();
}

private function createDict():void
{
	dictName2Type = new Dictionary();
	dictType2Button = new Dictionary;
	var item:Object;
	for each (item in acDiv)
	{
		var type:String = item.type;
		if (type == '99')
		{
			break;
		}
		/** 建立家電名稱對應到該家電號 */
		dictName2Type[item.name] = type;
		/** 建立家電號對應顯示按鈕 */
		var btn:Button;
		if (type.length == 1)
		{
			btn = this['divE' + '0' + type] as Button;
		}
		else
		{
			btn = this['divE' + type] as Button;
		}
		btn.mouseEnabled = false;
		btn.mouseChildren = false;
		btn.alpha = 0.3;
		dictType2Button[type] = btn;
	}
	createSelectorData();
}

private function createSelectorData():void
{
	acSelector = new ArrayCollection();
	var now:Date = new Date();
	for (var i:int; i < 12; i++)
	{
		var date:Date   = new Date(now.fullYear, now.month - i, 1);
		var item:Object = new Object();
		item.label = getYearMonthC(date);
		item.data = date;
		acSelector.addItem(item);
	}
	acSelector.refresh();
	cbSelector.selectedIndex = 0;
	queryDate = cbSelector.selectedItem.data as Date;
	strTimeRange = getYearMonth(queryDate);
	fetchHome();
}

/** ComboBox 選取後所觸發的事件 */
private function selectorChange(event:ListEvent):void
{
	var item:Object = cbSelector.selectedItem;
	var start:Date  = item.data as Date;
	if (start.getTime() > new Date().getTime())
	{
		alertStartError();
		return;
	}
	queryDate = start;
	queryInterval = MONTH;
	getData();
}

private function fetchHome():void
{
	var service:HTTPService = new HTTPService();
	var url:String          = uriHome;
	url += '?electricid=' + electricid;
	service.url = url;
	trace(url);
	service.addEventListener(ResultEvent.RESULT, homeResult);
	newLoading();
	service.send();
}

private function homeResult(event:ResultEvent):void
{
	delLoading();
	var result:Object = event.result;
	if (result.equipment.equip_ID is ArrayCollection)
	{
		var equipIDS:ArrayCollection = result.equipment.equip_ID as ArrayCollection;
		var btn:Button;
		for each (var ID:String in equipIDS)
		{
			var temp:Array      = ID.split('-');
			var ac:ArrayCollection;
			var typeNum:String  = temp[0];
			var countNum:Number = Number(temp[1]);
			btn = dictType2Button[typeNum] as Button;
			if (acButton.getItemIndex(btn) < 0)
			{
				acButton.addItem(btn);
			}
			if (dictButton2Count.hasOwnProperty(btn))
			{
				ac = dictButton2Count[btn] as ArrayCollection;
				ac.addItem(countNum);
			}
			else
			{
				ac = new ArrayCollection();
				ac.addItem(countNum);
				dictButton2Count[btn] = ac;
			}
		}
		var str:String = '電器資料如下:\n';
		for each (btn in acButton)
		{
			btn.mouseEnabled = true;
			btn.mouseChildren = true;
			btn.alpha = 1;
			btn.toggle = true;
			btn.addEventListener(MouseEvent.MOUSE_DOWN, homeClick);
			str += btn.toolTip + '\n';
		}
		Alert.show(str);
	}
}

private function homeClick(event:MouseEvent):void
{
	var target:Button = event.currentTarget as Button;
	/** 設定button選取與否 */
	if (!target.selected)
	{
		for each (var btn:Button in acButton)
		{
			if (btn.selected)
			{
				btn.selected = false;
			}
		}
	}
	target.selected = true;
	_contentName = target.toolTip;
	/** 抓取button所持有的數量 */
	var ac:ArrayCollection = dictButton2Count[target] as ArrayCollection;
	if (ac.length == 1)
	{
		_contentID = dictName2Type[_contentName] + '-' + ac.getItemAt(0).toString()
		getData();
	}
	else
	{
		var temp:ArrayCollection = new ArrayCollection();
		for each (var count:Object in ac)
		{
			var item:Object = new Object();
			item.label = _contentName + '-' + count.toString();
			item.data = dictName2Type[_contentName] + '-' + count.toString();
			temp.addItem(item);
		}
		createHomeBox(temp, event.stageX, event.stageY);
	}
}

private function createHomeBox(ac:ArrayCollection, _x:Number, _y:Number):void
{
	_homebox = PopUpManager.createPopUp(this, homeBox, true) as homeBox;
	_homebox.homeData = ac;
	_homebox.x = _x;
	_homebox.y = _y;
	_homebox.height = (ac.length + 1) * 32;
	_homebox.title = _contentName;
	_homebox.homeList.addEventListener(ListEvent.ITEM_CLICK, homeItemClick);
}

private function homeItemClick(event:ListEvent):void
{
	var list:List          = event.currentTarget as List;
	var ac:ArrayCollection = list.dataProvider as ArrayCollection;
	var item:Object        = ac.getItemAt(event.rowIndex);
	_contentID = item.data;
	getData();
	deleteHomeBox();
}

private function deleteHomeBox():void
{
	if (_homebox != null)
	{
		PopUpManager.removePopUp(_homebox);
	}
}

private function columnClick(event:ChartItemEvent):void
{
	var item:Object = event.hitData.item;
	var date:Date   = item.TimeStamp as Date;
	switch (columnAxis.dataUnits)
	{
		case MONTHS:
		{
			/** 年資料，圖表時間單位為月，點擊後呈現該月的日資料 */
			queryDate = new Date(date.fullYear, date.month, 1);
			queryInterval = MONTH;
			getData();
			break;
		}
		case DAYS:
		{
			/** 月資料，圖表時間單位為日，點擊後呈現該日的小時資料 */
			queryDate = new Date(date.fullYear, date.month, date.date);
			queryInterval = DAY;
			getData();
			break;
		}
		case HOURS:
		{
			return;
			break;
		}
	}
}

private function getData():void
{
	if (_contentID == '')
	{
		Alert.show('請先選擇一項電器');
		return;
	}
	var service:HTTPService = new HTTPService();
	var s:String            = getFullDate(queryDate);
	var siteUrl:String      = uriData;
	siteUrl += "?starttime=" + s;
	siteUrl += "&electricid=" + electricid;
	siteUrl += "&interval=" + queryInterval;
	siteUrl += "&eqpid=" + _contentID;
	service.url = siteUrl;
	trace(service.url);
	switch (queryInterval)
	{
		case YEAR:
		case MONTH:
		{
			columnChart.type = "stacked";
			break;
		}
		case DAY:
		{
			columnChart.type = "clusterrd";
			break;
		}
	}
	service.addEventListener(ResultEvent.RESULT, getResult);
	service.addEventListener(FaultEvent.FAULT, getFault);
	noData = false;
	newLoading();
	acColumn.removeAll();
	acRatio.removeAll();
	service.send();
}

private function getFault(event:FaultEvent):void
{
	delLoading();
	Alert.show(event.fault.faultString);
}

private function getResult(event:ResultEvent):void
{
	var s:Date = queryDate;
	switch (queryInterval)
	{
		case YEAR:
		{
			strTimeRange = s.fullYear.toString();
			break;
		}
		case MONTH:
		{
			strTimeRange = getYearMonth(s);
			break;
		}
		case DAY:
		{
			strTimeRange = getDate(s);
			break;
		}
	}
	delLoading();
	var item:Object;
	var data:Object = event.result.data;
	item = data.bar;
	setColumn(item as ArrayCollection);
	/** setRatio **/
	item = data.home;
	setRatio(item.Eqp as ArrayCollection);
	var arr:Array = [];
	arr[_contentIndex] = 0.2;
	pieSeries.perWedgeExplodeRadius = arr;
}

private function setRatio(source:ArrayCollection):void
{
	if (source == null)
	{
		return;
	}
	for each (var item:Object in source)
	{
		item.equip_usage = item.equip_usage;
		if (_contentID == item.equip_ID)
		{
			_contentIndex = source.getItemIndex(item);
		}
		var index:int = String(item.equip_ID).indexOf('-');
		if (index > -1)
		{
			var array:Array = String(item.equip_ID).split('-');
			item.label = Button(dictType2Button[array[0]]).toolTip + '-' + array[1].toString();
		}
		else
		{
			item.label = '其他';
		}
	}
	acRatio = source;
	acRatio.refresh();
}

private function setColumn(source:ArrayCollection):void
{
	if (source == null)
	{
		noData = true;
		return;
	}
	setColumnSeries(true);
	max = 0;
	var item:Object;
	var start:Number = new Date().getTime();
	var end:Number   = 0;
	for each (item in source)
	{
		var temp:String = item.TimeStamp;
		temp = temp.replace(/-/g, "/");
		var num:Number = Date.parse(temp);
		if (num >= end)
		{
			end = num;
		}
		if (start >= num)
		{
			start = num;
		}
		item.TimeStamp = new Date(num);
		var total:Number = 0;
		item.Rate_A = Number(item.Rate_A);
		item.Rate_C = Number(item.Rate_C);
		item.Rate_D = Number(item.Rate_D);
		item.Rate_N = Math.max(item.Rate_A, item.Rate_C, item.Rate_D);
		if (item.Rate_N == item.Rate_A)
		{
			item.Fill = 'a';
		}
		if (item.Rate_N == item.Rate_C)
		{
			item.Fill = 'c';
		}
		if (item.Rate_N == item.Rate_D)
		{
			item.Fill = 'd';
		}
		total += item.Rate_A + item.Rate_C + item.Rate_D;
		if (total > max)
		{
			max = total;
		}
		item.Rate = total;
		if (queryInterval == DAY)
		{
			item.Rate_A = 0;
			item.Rate_C = 0;
			item.Rate_D = 0;
		}
	}
	var s:Date = new Date(start);
	var e:Date = new Date(end);
	switch (queryInterval)
	{
		case YEAR:
		{
			strTimeRange = s.fullYear.toString();
			columnAxis.dataUnits = MONTHS;
			break;
		}
		case MONTH:
		{
			strTimeRange = getYearMonth(s);
			columnAxis.dataUnits = DAYS;
			break;
		}
		case DAY:
		{
			strTimeRange = getDate(s);
			columnAxis.dataUnits = HOURS;
			setColumnSeries(false);
			break;
		}
	}
	acColumn = source;
	acColumn.refresh();
}

private function setColumnSeries(bool:Boolean):void
{
	csA.visible = bool;
	csC.visible = bool;
	csD.visible = bool;
	csN.visible = !bool;
}

private function colorFunc(item:ChartItem, index:Number):IFill
{
	var data:Object   = item.item;
	var sc:SolidColor = new SolidColor(0);
	switch (data.Fill)
	{
		case 'a':
		{
			sc = scA;
			break;
		}
		case 'c':
		{
			sc = scC;
			break;
		}
		case 'd':
		{
			sc = scD;
			break;
		}
	}
	return sc;
}

private function columnDataTipFunction(e:HitData):String
{
	var result:String;
	var series:ColumnSeries    = e.element as ColumnSeries;
	var sitem:ColumnSeriesItem = e.chartItem as ColumnSeriesItem;
	var item:Object            = e.item;
	var yField:Number          = Number(e.item[series.yField]);
	if (isNaN(yField) || yField == 0)
	{
		return '';
	}
	var yValue:Number = Number(item.Rate);
	var ratio:Number  = (yField / yValue) * 100;
	switch (columnChart.type)
	{
		case "stacked":
		{
			result = "類別：" + series.displayName;
			result += "\n" + "時間：" + getDate(item.TimeStamp);
			result += "\n" + "數值：" + yField.toFixed(digitEquip) + " kWh" + "　(" + ratio.toFixed(digitEquip) + "%)";
			result += "\n" + "總值：" + yValue.toFixed(digitEquip) + " kWh";
			break;
		}
		case "clusterrd":
		{
			result = "類別：";
			if (item.Fill == 'a')
			{
				result += '尖峰';
			}
			else if (item.Fill == 'c')
			{
				result += '離峰';
			}
			else if (item.Fill == 'd')
			{
				result += '周末半尖峰';
			}
			result += "\n" + "時間：" + getTime(item.TimeStamp);
			result += "\n" + "數值：" + yField.toFixed(digitEquip) + " kWh";
			break;
		}
	}
	return result;
}

private function pieDataTipFunction(e:HitData):String
{
	var result:String       = '';
	var series:PieSeries    = e.element as PieSeries;
	var sitem:PieSeriesItem = e.chartItem as PieSeriesItem;
	var item:Object         = e.item;
	var ratio:Number        = Number(item.equip_usage);
	result = "電器: " + item.label;
	result += "\n" + "電量: " + ratio.toFixed(digitEquip) + " kWh";
	result += "\n" + "比例: " + sitem.percentValue.toFixed(digitEquip) + " %";
	return result;
}

private function switchRange(event:MouseEvent):void
{
	switch (event.currentTarget)
	{
		case btnDay:
		{
			if (queryInterval == YEAR)
			{
				/** 在年資料的情況下，按下天 */
				queryInterval = DAY;
				queryDate = new Date(queryDate.fullYear, 0, 1);
				getData();
			}
			else if (queryInterval == MONTH)
			{
				/** 在月資料的情況下，按下天 */
				queryInterval = DAY;
				queryDate = new Date(queryDate.fullYear, queryDate.month, 1);
				getData();
			}
			break;
		}
		case btnMonth:
		{
			if (queryInterval == YEAR)
			{
				/** 在年資料的情況下，按下月 */
				queryInterval = MONTH;
				queryDate = new Date(queryDate.fullYear, 0, 1);
				getData();
			}
			else if (queryInterval == DAY)
			{
				/** 在天資料的情況下，按下月 */
				queryInterval = MONTH;
				queryDate = new Date(queryDate.fullYear, queryDate.month, 1);
				getData();
			}
			break;
		}
		case btnYear:
		{
			if (queryInterval == MONTH)
			{
				/** 在月資料的情況下，按下年
				 *  該顯示當年度一整年的資料 */
				queryInterval = YEAR;
				queryDate = new Date(queryDate.fullYear, 0, 1);
				getData();
			}
			else if (queryInterval == DAY)
			{
				/** 在天資料的情況下，按下年。
				 *  該顯示當年初至當天的資料 */
				queryInterval = YEAR;
				queryDate = new Date(queryDate.fullYear, 0, 1);
				getData();
			}
			break;
		}
	}
}

private function scrollRange(event:MouseEvent):void
{
	var style:String = (event.currentTarget as Button).styleName.toString();
	style = style.replace('btn', '');
	switch (queryInterval)
	{
		case YEAR:
		{
			if (style == "Left")
			{
				queryDate = new Date(queryDate.fullYear - 1, 0, 1);
			}
			else if (style == "Right")
			{
				queryDate = new Date(queryDate.fullYear + 1, 0, 1);
			}
			break;
		}
		case MONTH:
		{
			if (style == "Left")
			{
				queryDate = new Date(queryDate.fullYear, queryDate.month - 1, 1);
			}
			else if (style == "Right")
			{
				queryDate = new Date(queryDate.fullYear, queryDate.month + 1, 1);
			}
			break;
		}
		case DAY:
		{
			if (style == "Left")
			{
				queryDate = new Date(queryDate.fullYear, queryDate.month, queryDate.date - 1);
			}
			else if (style == "Right")
			{
				queryDate = new Date(queryDate.fullYear, queryDate.month, queryDate.date + 1);
			}
			break;
		}
	}
	getData();
}

private function newLoading():void
{
	loading = PopUpManager.createPopUp(this, loadingBox, true) as loadingBox;
	loading.x = (this.width - loading.width) / 2;
	loading.y = (this.height - loading.height) / 2;
}

private function delLoading():void
{
	if (loading != null)
	{
		PopUpManager.removePopUp(loading);
		loading = null;
	}
}

private function alertStartError():void
{
	Alert.show(startError);
}

private function dateLabelFunction(value:Date, lastValue:Date, asix:DateTimeAxis):String
{
	var result:String;
	switch (columnAxis.dataUnits)
	{
		case "months":
		{
			result = getYearMonth(value);
			break;
		}
		case "days":
		{
			result = getMonthDay(value);
			break;
		}
		case "hours":
		{
			result = getHourMinute(value);
			break;
		}
	}
	return result;
}
